<template>
	<view :class="['container', { 'dark-mode': isDarkMode }, currentTheme]" @touchstart="handleTouchStart"
		@touchmove="handleTouchMove" @touchend="handleTouchEnd">
		<view class="theme-ripple" :style="rippleStyle"></view>
		<view class="fixed-header">
			<view class="statistics-card">
				<view class="stat-content">
					<view class="stat-item">
						<text class="stat-value">¥{{ dashboardData.totalAmount }}</text>
						<text class="stat-label">礼金总额</text>
					</view>
					<view class="stat-divider"></view>
					<view class="stat-item">
						<text class="stat-value">{{ dashboardData.guestCount }}</text>
						<text class="stat-label">来宾人数</text>
					</view>
				</view>
			</view>

			<view class="quick-actions">
				<view class="action-btn primary" @tap="showAddModal" v-if="dashboardData.write">
					<view class="big-jia bigfont"></view>
					<text>添加记录</text>
				</view>
				<view class="action-btn secondary" @tap="exportData">
					<view class="big-24px bigfont" style="font-size: 20px;"></view>
					<text>导出数据</text>
				</view>
			</view>

			<view class="search-section">
				<view class="search-bar">
					<text class="search-icon bigfont big-sousuo"></text>
					<input type="text" v-model="searchText" @input="handleSearch" placeholder="搜索姓名"
						class="search-input" />
				</view>
			</view>
		</view>

		<view class="content-wrapper">
			<scroll-view scroll-y="true" class="gift-list" :class="{ 'has-data': giftList.length > 0 }"
				refresher-enabled @refresherrefresh="onRefresh" :refresher-triggered="isRefreshing"
				@scrolltolower="loadMore">
				<view v-for="(item, index) in giftList" :key="index" class="gift-item"
					@tap="dashboardData.write ? showEditModal(item) : null">
					<view class="gift-info">
						<view class="gift-main">
							<view class="guest-info">
								<text class="guest-name">{{ item.name }}</text>
								<text class="gift-type-tag" :style="getTagStyle(item.type)">{{ item.type }}</text>
							</view>
							<view class="gift-amount">
								<text class="amount">¥{{ formatAmount(item.amount) }}</text>
								<text class="amount-chinese">{{ convertCurrency(Number(item.amount)) }}</text>
							</view>
						</view>
						<view class="gift-details">
							<text class="gift-date">{{ formatDisplayDate(item.date) }}</text>
							<text class="gift-remark" v-if="item.remarks">{{ item.remarks }}</text>
						</view>
					</view>
				</view>
				<view class="loading-more" v-if="isLoading">加载中...</view>
				<view class="no-more" v-if="!hasMore && giftList.length > 0">没有更多数据了</view>
				<view class="empty-state" v-if="giftList.length === 0">
					<image class="empty-icon"
						src="https://files.bigtian.club/bigtian/2024/12/18/20241218143338A002.png"></image>
					<text class="empty-text">暂无记录</text>
				</view>
			</scroll-view>
		</view>

		<!-- 添加/编辑弹窗 -->
		<view class="modal" v-if="showModal" @tap="closeModal">
			<view class="modal-content" @tap.stop>
				<view class="modal-header">
					<text class="modal-title">{{ isEditing ? '编辑' : '添加' }}</text>
					<text class="modal-close" @tap="closeModal">×</text>
				</view>
				<view class="modal-body">
					<view class="form-group">
						<view class="form-item">
							<text class="form-label required">姓名</text>
							<input type="text" v-model="currentGift.name" placeholder="请输入姓名" class="form-input" />
						</view>
						<view class="form-item">
							<text class="form-label required">金额</text>
							<input type="digit" v-model="currentGift.amount" placeholder="请输入金额"
								class="form-input money" @input="handleAmountInput" @blur="handleAmountBlur"
								maxlength="10" />
						</view>
					</view>
					<view class="form-group">
						<view class="form-item">
							<text class="form-label required">日期</text>
							<picker mode="date" :value="currentGift.date" @change="onDateChange" class="form-picker">
								<view class="picker-text">{{ currentGift.date || '请选择日期' }}</view>
							</picker>
						</view>
						<view class="form-item">
							<text class="form-label required">类型</text>
							<picker :range="giftTypes" :value="giftTypeIndex" @change="onTypeChange"
								class="form-picker">
								<view class="picker-text">{{ currentGift.type || '请选择类型' }}</view>
							</picker>
						</view>
					</view>
					<view class="form-item">
						<text class="form-label">备注</text>
						<textarea v-model="currentGift.remarks" placeholder="请输入备注信息" class="form-textarea" />
					</view>
				</view>
				<view class="modal-footer">
					<button class="modal-btn cancel" @tap="closeModal">取消</button>
					<button class="modal-btn confirm" @tap="saveGift">确定</button>
				</view>
			</view>
		</view>

		<!-- 导出选项弹窗 -->
		<view class="export-modal" v-if="showExportOptions" @tap="closeExportOptions">
			<view class="export-content" @tap.stop>
				<view class="export-header">
					<text class="export-title">导出选项</text>
					<text class="export-close bigfont big-guanbi" @tap="closeExportOptions"></text>
				</view>
				<view class="export-options">
					<view class="export-option" @tap="handleExportOption('open')">
						<view class="option-icon-wrapper">
							<text class="option-icon bigfont big-eye"></text>
						</view>
						<view class="option-info">
							<text class="option-title">打开文件</text>
							<text class="option-desc">在本地打开导出的Excel文件</text>
						</view>
					</view>
					<view class="export-option" @tap="handleExportOption('share')">
						<view class="option-icon-wrapper">
							<text class="option-icon bigfont big-fenxiang"></text>
						</view>
						<view class="option-info">
							<text class="option-title">分享给好友</text>
							<text class="option-desc">将Excel文件转发给微信好友</text>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { getGiftBookDetail } from '@/api/giftBook';
import {
	addGiftRecord,
	exportGiftRecords,
	getGiftRecordsDashboard,
	getGiftRecordsList,
	updateGiftRecord
} from '@/api/giftRecords';
import { convertCurrency } from '@/utils/money';
import { computed, onMounted, ref } from 'vue';

// 左滑返回相关变量
const touchStartX = ref(0);
const touchStartY = ref(0);
const minSwipeDistance = 100; // 最小滑动距离
const maxVerticalDistance = 50; // 最大垂直距离

// 处理触摸开始
const handleTouchStart = (e) => {
	touchStartX.value = e.touches[0].clientX;
	touchStartY.value = e.touches[0].clientY;
};

// 处理触摸移动
const handleTouchMove = (e) => {
	if (!touchStartX.value) return;

	const touchEndX = e.touches[0].clientX;
	const touchEndY = e.touches[0].clientY;

	// 计算水平和垂直距离
	const deltaX = touchEndX - touchStartX.value;
	const deltaY = Math.abs(touchEndY - touchStartY.value);

	// 如果是向右滑动，且垂直移动距离不太大
	if (deltaX > minSwipeDistance && deltaY < maxVerticalDistance) {
		// 重置触摸起始点
		touchStartX.value = 0;
		touchStartY.value = 0;
		// 执行返回操作
		backToHome();
	}
};

// 处理触摸结束
const handleTouchEnd = () => {
	// 重置触摸起始点
	touchStartX.value = 0;
	touchStartY.value = 0;
};

// 模式状态
const isDarkMode = ref(false);

// 初始化暗黑模式状态
const initDarkMode = () => {
	const savedMode = uni.getStorageSync('isDarkMode');
	isDarkMode.value = savedMode === true;
	updateNavigationBarStyle();
};

// 更新导航栏样式
const updateNavigationBarStyle = () => {
	uni.setNavigationBarColor({
		frontColor: isDarkMode.value ? '#ffffff' : '#000000',
		backgroundColor: isDarkMode.value ? '#1a1a1a' : '#F8F8F8',
		animation: {
			duration: 300,
			timingFunc: 'easeIn'
		}
	});
};

// 切换暗黑模式
const toggleTheme = () => {
	isDarkMode.value = !isDarkMode.value;
	uni.setStorageSync('isDarkMode', isDarkMode.value);
	updateNavigationBarStyle();
};

// 礼金类型
const giftTypes = ['礼金', '红包', '礼品', '其他'];
const giftTypeIndex = ref(0);

// 数据相关
const giftList = ref([]);
const searchText = ref('');
const showModal = ref(false);
const isEditing = ref(false);
const isRefreshing = ref(false);
const isLoading = ref(false);
const hasMore = ref(true);
const currentPage = ref(1);
const pageSize = ref(10);

// 格式化显示日期
const formatDisplayDate = (dateStr) => {
	const date = new Date(dateStr);
	const year = date.getFullYear();
	const month = String(date.getMonth() + 1).padStart(2, '0');
	const day = String(date.getDate()).padStart(2, '0');
	return `${year}年${month}月${day}日`;
};

// 格式化金额
const formatAmount = (amount) => {
	return Number(amount).toLocaleString('zh-CN', {
		minimumFractionDigits: 2,
		maximumFractionDigits: 2
	});
};

// 计算总金额数
const totalAmount = computed(() => {
	return formatAmount(giftList.value.reduce((sum, item) => sum + Number(item.amount), 0));
});

// 计算总金额中文
const totalAmountChinese = computed(() => {
	const amount = giftList.value.reduce((sum, item) => sum + Number(item.amount), 0);
	return convertCurrency(amount);
});

// 格式化日期
const formatDate = (date) => {
	const year = date.getFullYear();
	const month = String(date.getMonth() + 1).padStart(2, '0');
	const day = String(date.getDate()).padStart(2, '0');
	return `${year}-${month}-${day}`;
};

// 当前编辑的礼金记录
const currentGift = ref({
	id: '',
	name: '',
	amount: '',
	date: formatDate(new Date()),
	type: '礼金',
	remarks: '',
	bookId: ''
});

// 长按标志
let isLongPress = false;

// 搜索防抖
let searchTimer = null;
const handleSearch = () => {
	if (searchTimer) {
		clearTimeout(searchTimer);
	}
	searchTimer = setTimeout(() => {
		// 重置页码并重新获取数据
		currentPage.value = 1;
		fetchGiftRecords(1, pageSize.value, searchText.value);
	}, 500);
};

// 搜索过滤
const filteredGiftList = computed(() => {
	if (!searchText.value) return giftList.value;
	const keyword = searchText.value.toLowerCase();
	return giftList.value.filter(item =>
		item.name.toLowerCase().includes(keyword) ||
		(item.remarks && item.remarks.toLowerCase().includes(keyword))
	);
});

// 显示添加弹窗
const showAddModal = () => {
	isEditing.value = false;
	currentGift.value = {
		id: '',
		name: '',
		amount: '',
		date: formatDate(new Date()),
		type: '礼金',
		remarks: '',
		bookId: currentBookId.value
	};
	giftTypeIndex.value = 0;
	showModal.value = true;
};

// 显示编辑弹窗
const showEditModal = async (item) => {
	isEditing.value = true;
	currentGift.value = {
		...item,
		date: item.date.split(' ')[0] // 只保留日期部分，去掉时间
	};
	// 设置类型索引
	giftTypeIndex.value = giftTypes.indexOf(item.type);
	showModal.value = true;
};

// 关闭弹窗
const closeModal = () => {
	showModal.value = false;
};

// 日期选择处理
const onDateChange = (e) => {
	currentGift.value.date = e.detail.value;
};

// 类型选择处理
const onTypeChange = (e) => {
	giftTypeIndex.value = e.detail.value;
	currentGift.value.type = giftTypes[e.detail.value];
};

// 保存礼金记录
const saveGift = async () => {
	if (!currentGift.value.name || !currentGift.value.amount || !currentGift.value.date) {
		uni.showToast({
			title: '请填写完整信息',
			icon: 'none'
		});
		return;
	}

	// 验证金额格式
	if (!/^\d+(\.\d{0,2})?$/.test(currentGift.value.amount)) {
		uni.showToast({
			title: '请输入正确的金额格式',
			icon: 'none'
		});
		return;
	}

	const giftData = {
		...currentGift.value,
		amount: Number(currentGift.value.amount).toFixed(2),
		bookId: currentBookId.value
	};

	try {
		const response = isEditing.value
			? await updateGiftRecord(giftData)
			: await addGiftRecord(giftData);

		if (response.code === 200) {
			showModal.value = false;
			// 刷新列表数据和统计数据
			fetchGiftRecords();
			fetchDashboardData();
			uni.showToast({
				title: `${isEditing.value ? '修改' : '添加'}成功`,
				icon: 'success'
			});
		} else {
			uni.showToast({
				title: response.msg || `${isEditing.value ? '修改' : '添加'}失败`,
				icon: 'none'
			});
		}
	} catch (error) {
		console.error('保存礼簿记录失败:', error);
		uni.showToast({
			title: '网络请求失败',
			icon: 'none'
		});
	}
};

// 导出选项状态
const showExportOptions = ref(false);
const exportFilePath = ref('');
const exportFileName = ref('');

// 关闭导出选项
const closeExportOptions = () => {
	showExportOptions.value = false;
};

// 处理导出选项
const handleExportOption = (type) => {
	if (type === 'open') {
		// 打开文件
		wx.openDocument({
			filePath: exportFilePath.value,
			fileType: 'xlsx',
			showMenu: true,
			success: () => {
				console.log('文件打开成功');
				uni.hideLoading();
				uni.showToast({
					title: '导出成功',
					icon: 'success'
				});
				closeExportOptions();
			},
			fail: (err) => {
				console.error('打开文件失败:', err);
				uni.hideLoading();
				uni.showModal({
					title: '打开文件失败',
					content: err.errMsg || '请稍后重试',
					showCancel: false
				});
			}
		});
	} else if (type === 'share') {
		// 转发文件给好友
		wx.shareFileMessage({
			filePath: exportFilePath.value,
			fileName: exportFileName.value,
			success: () => {
				console.log('文件分享成功');
				uni.hideLoading();
				uni.showToast({
					title: '分享成功',
					icon: 'success'
				});
				closeExportOptions();
			},
			fail: (err) => {
				console.error('文件分享失败:', err);
				uni.hideLoading();
				uni.showModal({
					title: '分享失败',
					content: err.errMsg || '请稍后重试',
					showCancel: false
				});
			}
		});
	}
};

// 修改导出数据函数
const exportData = async () => {
	// 如果没有数据，提示用户
	if (giftList.value.length === 0) {
		uni.showToast({
			title: '暂无数据可导出',
			icon: 'none'
		});
		return;
	}

	try {
		uni.showLoading({
			title: '正在导出...',
			mask: true
		});
		const response = await exportGiftRecords(currentBookId.value);

		if (!response) {
			throw new Error('导出失败：未收到响应数据');
		}

		if (response instanceof ArrayBuffer) {
		} else {
			throw new Error('导出失败：响应格式不正确');
		}

		// 获取当前时间作为文件名的一部分
		const now = new Date();
		const timestamp = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}`;
		const fileName = `${bookTitle.value || '礼簿记录'}_${timestamp}.xlsx`;

		// #ifdef MP-WEIXIN
		const filePath = `${wx.env.USER_DATA_PATH}/${fileName}`;

		// 保存文件到本地
		const fs = wx.getFileSystemManager();

		try {
			// 直接写入二进制数据
			fs.writeFileSync(
				filePath,
				response,
				'binary'
			);

			// 保存文件路径和名称
			exportFilePath.value = filePath;
			exportFileName.value = fileName;

			// 显示自定义导出选项
			showExportOptions.value = true;
			uni.hideLoading();

		} catch (fsError) {
			console.error('文件系统操作失败:', fsError);
			uni.hideLoading();
			uni.showModal({
				title: '保存文件失败',
				content: fsError.message || '请稍后重试',
				showCancel: false
			});
		}
		// #endif

		// #ifdef H5
		// 创建下载链接
		const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
		const link = document.createElement('a');
		link.href = URL.createObjectURL(blob);
		link.download = fileName;
		link.click();
		URL.revokeObjectURL(link.href);
		uni.hideLoading();
		uni.showToast({
			title: '导出成功',
			icon: 'success'
		});
		// #endif
	} catch (error) {
		console.error('导出失败:', error);
		uni.hideLoading();
		uni.showModal({
			title: '导出失败',
			content: error.message || '请稍后重试',
			showCancel: false
		});
	}
};

// 下拉刷新
const onRefresh = async () => {
	isRefreshing.value = true;
	try {
		await fetchGiftRecords();
	} finally {
		isRefreshing.value = false;
	}
};

// 主题切换按钮位置
const switchPosition = ref({
	x: uni.getStorageSync('themeSwitchX') || 30,
	y: uni.getStorageSync('themeSwitchY') || uni.getSystemInfoSync().windowHeight / 2
});

// 触摸起始点
const touchStartPoint = ref({ x: 0, y: 0 });
const startPosition = ref({ x: 0, y: 0 });

// 计算按钮样式
const switchStyle = computed(() => {
	return {
		transform: `translate3d(${switchPosition.value.x}px, ${switchPosition.value.y}px, 0)`,
		transition: touchStartPoint.value.x === 0 ? 'transform 0.3s ease' : 'none'
	}
});

// 触摸开始
const touchStart = (e) => {
	isLongPress = false;
	const touch = e.touches[0];
	touchStartPoint.value = {
		x: touch.clientX,
		y: touch.clientY
	};
	startPosition.value = {
		x: switchPosition.value.x,
		y: switchPosition.value.y
	};
};

// 触摸移动
const touchMove = (e) => {
	if (touchStartPoint.value.x === 0) return;

	const touch = e.touches[0];
	const deltaX = touch.clientX - touchStartPoint.value.x;
	const deltaY = touch.clientY - touchStartPoint.value.y;

	// 如果移动距离小于5px，进行移动
	if (Math.abs(deltaX) < 5 && Math.abs(deltaY) < 5) return;

	let newX = startPosition.value.x + deltaX;
	let newY = startPosition.value.y + deltaY;

	// 获取屏幕尺寸
	const systemInfo = uni.getSystemInfoSync();
	// 将rpx转换为px
	const buttonSize = 80 * (systemInfo.windowWidth / 750);
	const maxX = systemInfo.windowWidth - buttonSize;
	const maxY = systemInfo.windowHeight - buttonSize;

	// 限制在屏幕内
	newX = Math.max(0, Math.min(newX, maxX));
	newY = Math.max(0, Math.min(newY, maxY));

	switchPosition.value = { x: newX, y: newY };
};

// 触摸结束
const touchEnd = (e) => {
	// 如果是长按，不触发点击
	if (isLongPress) {
		isLongPress = false;
		return;
	}

	// 如果移动距离很小，视为点击
	const touch = e.changedTouches[0];
	const deltaX = touch.clientX - touchStartPoint.value.x;
	const deltaY = touch.clientY - touchStartPoint.value.y;

	if (Math.abs(deltaX) < 5 && Math.abs(deltaY) < 5) {
		toggleTheme();
		return;
	}

	// 重置触摸起始点
	touchStartPoint.value = { x: 0, y: 0 };

	// 获取屏幕尺寸
	const systemInfo = uni.getSystemInfoSync();
	const screenWidth = systemInfo.windowWidth;
	// 将rpx转换为px
	const buttonSize = 80 * (systemInfo.windowWidth / 750);
	const maxX = systemInfo.windowWidth - buttonSize;

	// 吸附到最近的边缘
	const finalX = switchPosition.value.x > screenWidth / 2 ? maxX : 0;

	// 应用吸附动画
	switchPosition.value = {
		x: finalX,
		y: switchPosition.value.y
	};

	// 保存位置到本地存储
	uni.setStorageSync('themeSwitchX', finalX);
	uni.setStorageSync('themeSwitchY', switchPosition.value.y);
};

// 页面加载时初始化
onMounted(() => {
	initDarkMode();
	// 获取页面参数
	const pages = getCurrentPages();
	const page = pages[pages.length - 1];
	const bookId = page.$page?.fullPath?.split('id=')[1];
	if (!bookId) {
		uni.showToast({
			title: '参数错误',
			icon: 'none'
		});
		setTimeout(() => {
			uni.navigateBack();
		}, 1500);
		return;
	}
	currentBookId.value = bookId;

	// 获取礼簿详情
	fetchBookDetail(bookId);

	// 获取统计数据和列表数据
	fetchDashboardData();
	if (giftList.value.length === 0) {
		fetchGiftRecords();
	}
});

// 主题相关
const themes = [
	{ id: 'theme-default', name: '默认主题', colors: { primary: '#8E2DE2', secondary: '#4A00E0' } },
	{ id: 'theme-wedding', name: '婚礼主题', colors: { primary: '#FF9999', secondary: '#FF5E5E' } },
	{ id: 'theme-baby', name: '满月主题', colors: { primary: '#5B9EE7', secondary: '#4A7FBA' } },
];

const currentTheme = ref(uni.getStorageSync('currentTheme') || 'theme-baby');
const rippleActive = ref(false);
const ripplePosition = ref({ x: 0, y: 0 });

// 计算涟漪样式
const rippleStyle = computed(() => {
	if (!rippleActive.value) return { display: 'none' };

	// 计算涟漪大小（屏幕对角线长度）
	const systemInfo = uni.getSystemInfoSync();
	const maxSize = Math.sqrt(
		Math.pow(systemInfo.windowWidth, 2) +
		Math.pow(systemInfo.windowHeight, 2)
	) * 2;

	return {
		position: 'fixed',
		left: ripplePosition.value.x + 'px',
		top: ripplePosition.value.y + 'px',
		width: maxSize + 'px',
		height: maxSize + 'px',
		transform: `translate(-50%, -50%) scale(${rippleActive.value ? 1 : 0})`,
		backgroundColor: isDarkMode.value ? '#1a1a1a' : '#F6F7FB',
		transition: 'transform 0.6s cubic-bezier(0.4, 0, 0.2, 1)',
		zIndex: 100,
		borderRadius: '50%',
		pointerEvents: 'none'
	};
});

// 长按主题切换按钮显示主题选择
const showThemeSelect = (e) => {
	isLongPress = true;
	// 阻止事件冒泡
	e.stopPropagation();
	// 阻止默认行为
	e.preventDefault();

	uni.showActionSheet({
		itemList: themes.map(theme => theme.name),
		success: (res) => {
			const selectedTheme = themes[res.tapIndex];
			if (selectedTheme && selectedTheme.id !== currentTheme.value) {
				// 只有当选择了不同的主题时才进行切换
				currentTheme.value = selectedTheme.id;
				uni.setStorageSync('currentTheme', selectedTheme.id);

				// // 触发涟漪效果
				// ripplePosition.value = {
				// 	x: switchPosition.value.x,
				// 	y: switchPosition.value.y
				// };
				// rippleActive.value = true;
				// setTimeout(() => {
				// 	rippleActive.value = false;
				// }, 600);
			}
		}
	});
};

const getTagStyle = (type) => {
	const themeColors = {
		'theme-default': {
			礼金: { light: '#8E2DE2', dark: '#A355E8' },
			红包: { light: '#FF5E5E', dark: '#FF7F7F' },
			礼品: { light: '#5B9EE7', dark: '#7BAEF0' },
			其他: { light: '#666666', dark: '#999999' }
		},
		'theme-wedding': {
			礼金: { light: '#FF9999', dark: '#FFB3B3' },
			红包: { light: '#FF5E5E', dark: '#FF7F7F' },
			礼品: { light: '#FF8080', dark: '#FFA3A3' },
			其他: { light: '#FF6666', dark: '#FF8989' }
		},
		'theme-baby': {
			礼金: { light: '#5B9EE7', dark: '#7BAEF0' },
			红包: { light: '#4A7FBA', dark: '#6A9FD0' },
			礼品: { light: '#6AAFE8', dark: '#8ABFEF' },
			其他: { light: '#4A8BCE', dark: '#6AA1D8' }
		},
		'theme-mourn': {
			礼金: { light: '#666666', dark: '#999999' },
			红包: { light: '#555555', dark: '#888888' },
			礼品: { light: '#777777', dark: '#AAAAAA' },
			其他: { light: '#444444', dark: '#777777' }
		}
	};

	const currentThemeColors = themeColors[currentTheme.value] || themeColors['theme-default'];
	const colorSet = currentThemeColors[type] || currentThemeColors['其他'];
	const color = isDarkMode.value ? colorSet.dark : colorSet.light;

	return {
		color: color,
		backgroundColor: `${color}15`,
		border: `1px solid ${color}30`
	};
};

// 获取当前礼簿信息
const bookTitle = ref('');
const currentBookId = ref('');

// 统计数据
const dashboardData = ref({
	totalAmount: '0.00',
	guestCount: 0,
	write: false
});

// 获取统计数据
const fetchDashboardData = async () => {
	try {
		const response = await getGiftRecordsDashboard(currentBookId.value);
		if (response.code === 200) {

			dashboardData.value = {
				totalAmount: response.data.totalAmount?.toFixed(2) || '0.00',
				guestCount: response.data.guestCount,
				write: response.data.writer
			};
		}
	} catch (error) {
		console.error('获取统计数据失败:', error);
	}
};

// 返回上一页
const backToHome = () => {
	uni.navigateBack({
		delta: 1
	});
};

// 验证金额输入
const validateAmount = (value) => {
	// 只允许输入数字和小数点
	const newValue = value.replace(/[^\d.]/g, '');
	// 确保只有一个小数点
	const parts = newValue.split('.');
	if (parts.length > 2) {
		return parts[0] + '.' + parts[1];
	}
	// 限制小数点后两位
	if (parts.length === 2 && parts[1].length > 2) {
		return parts[0] + '.' + parts[1].substring(0, 2);
	}
	return newValue;
};

// 处理金额输入
const handleAmountInput = (e) => {
	let value = e.detail.value;

	// 如果输入的不是数字或小数点，直接返回旧值
	if (!/^\d*\.?\d*$/.test(value)) {
		// 保留之前的有效值
		return currentGift.value.amount;
	}

	// 处理开头的0
	if (value.length > 1 && value.startsWith('0') && !value.startsWith('0.')) {
		value = value.replace(/^0+/, '');
	}

	// 处理多个小数点
	const parts = value.split('.');
	if (parts.length > 2) {
		value = parts[0] + '.' + parts.slice(1).join('');
	}

	// 限制小数点后两位
	if (parts.length === 2 && parts[1].length > 2) {
		value = parts[0] + '.' + parts[1].substring(0, 2);
	}

	// 如果是以小数点开头，添加前导零
	if (value.startsWith('.')) {
		value = '0' + value;
	}

	// 更新输入值
	currentGift.value.amount = value;
};

// 处理金额输入框失焦
const handleAmountBlur = () => {
	if (!currentGift.value.amount) return;

	// 移除末尾的小数点
	if (currentGift.value.amount.endsWith('.')) {
		currentGift.value.amount = currentGift.value.amount.slice(0, -1);
	}

	// 确保金额格式正确（两位小数）
	currentGift.value.amount = Number(currentGift.value.amount).toFixed(2);
};

// API配置
const API_BASE_URL = 'https://vue.bigtian.club/prod-api/';

// 获取礼簿记录
const fetchGiftRecords = async (pageNum = 1, pageSize = 10, searchKeyword = '', isLoadMore = false) => {
	if (isLoading.value) return;
	isLoading.value = true;

	try {
		const response = await getGiftRecordsList({
			pageNum,
			pageSize,
			bookId: currentBookId.value,
			name: searchKeyword,
			params: {}
		});

		if (response.code === 200) {
			const { records, totalRow, pageNumber } = response.data;

			// 更新列表数据
			if (isLoadMore) {
				giftList.value = [...giftList.value, ...(records || [])];
			} else {
				giftList.value = records || [];
			}

			// 更新分页状态
			currentPage.value = pageNumber;
			hasMore.value = giftList.value.length < totalRow;
		} else {
			uni.showToast({
				title: response.msg || '获取数据失败',
				icon: 'none'
			});
		}
	} catch (error) {
		console.error('获取礼簿记录失败:', error);
		uni.showToast({
			title: '网络请求失败',
			icon: 'none'
		});
	} finally {
		isLoading.value = false;
		isRefreshing.value = false;
	}
};

// 加载更多数据
const loadMore = () => {
	if (!hasMore.value || isLoading.value) return;
	fetchGiftRecords(currentPage.value + 1, pageSize.value, searchText.value, true);
};

// 获取礼簿详情
const fetchBookDetail = async (bookId) => {
	try {
		const response = await getGiftBookDetail(bookId);
		if (response.code === 200) {
			bookTitle.value = response.data.title;
			console.log('获取到礼簿标题:', bookTitle.value);
		} else {
			console.log('获取礼簿详情失败:', response.msg);
		}
	} catch (error) {
		console.error('获取礼簿详情接口错误:', error);
	}
};
</script>

<style>
/* 基础布局 */
.container {
	background-color: var(--theme-background);
	min-height: 100vh;
	height: 100vh;
	position: relative;
	transition: all 0.3s ease;
	overflow: hidden;
}

.fixed-header {
	position: fixed;
	top: 42px;
	left: 0;
	right: 0;
	z-index: 100;
	background-color: transparent;
	padding: 30rpx;
}

.content-wrapper {
	padding: 30rpx;
	padding-top: 650rpx;
	height: 100vh;
	box-sizing: border-box;
	background-color: transparent;
	overflow: hidden;
}

/* 主题颜色 - 亮色模式 */
.theme-default {
	--theme-primary: #8E2DE2;
	--theme-secondary: #4A00E0;
	--theme-gradient: linear-gradient(135deg, var(--theme-primary), var(--theme-secondary));
	--theme-background: #F6F7FB;
	--theme-card: #FFFFFF;
	--theme-text: #333333;
	--theme-text-secondary: #666666;
	--theme-text-light: #999999;
	--theme-primary-light: rgba(142, 45, 226, 0.08);
	--theme-primary-border: rgba(142, 45, 226, 0.15);
}

.theme-wedding {
	--theme-primary: #FF9999;
	--theme-secondary: #FF5E5E;
	--theme-gradient: linear-gradient(135deg, var(--theme-primary), var(--theme-secondary));
	--theme-background: #FFF6F6;
	--theme-card: #FFFFFF;
	--theme-text: #333333;
	--theme-text-secondary: #666666;
	--theme-text-light: #999999;
	--theme-primary-light: rgba(255, 153, 153, 0.08);
	--theme-primary-border: rgba(255, 153, 153, 0.15);
}

.theme-baby {
	--theme-primary: #5B9EE7;
	--theme-secondary: #4A7FBA;
	--theme-gradient: linear-gradient(135deg, var(--theme-primary), var(--theme-secondary));
	--theme-background: #F5F9FF;
	--theme-card: #FFFFFF;
	--theme-text: #333333;
	--theme-text-secondary: #666666;
	--theme-text-light: #999999;
	--theme-primary-light: rgba(91, 158, 231, 0.08);
	--theme-primary-border: rgba(91, 158, 231, 0.15);
}

/* 主题颜色 - 暗黑模式 */
.dark-mode.theme-default {
	--theme-primary: #8E2DE2;
	--theme-secondary: #4A00E0;
	--theme-gradient: linear-gradient(135deg, var(--theme-primary), var(--theme-secondary));
	--theme-background: #1a1a1a;
	--theme-card: #2d2d2d;
	--theme-text: #ffffff;
	--theme-text-secondary: #bbbbbb;
	--theme-text-light: #888888;
	--theme-primary-light: rgba(142, 45, 226, 0.15);
	--theme-primary-border: rgba(142, 45, 226, 0.25);
}

.dark-mode.theme-wedding {
	--theme-primary: #FF9999;
	--theme-secondary: #FF5E5E;
	--theme-gradient: linear-gradient(135deg, var(--theme-primary), var(--theme-secondary));
	--theme-background: #1a1a1a;
	--theme-card: #2d2d2d;
	--theme-text: #ffffff;
	--theme-text-secondary: #bbbbbb;
	--theme-text-light: #888888;
	--theme-primary-light: rgba(255, 153, 153, 0.15);
	--theme-primary-border: rgba(255, 153, 153, 0.25);
}

.dark-mode.theme-baby {
	--theme-primary: #5B9EE7;
	--theme-secondary: #4A7FBA;
	--theme-gradient: linear-gradient(135deg, var(--theme-primary), var(--theme-secondary));
	--theme-background: #1a1a1a;
	--theme-card: #2d2d2d;
	--theme-text: #ffffff;
	--theme-text-secondary: #bbbbbb;
	--theme-text-light: #888888;
	--theme-primary-light: rgba(91, 158, 231, 0.15);
	--theme-primary-border: rgba(91, 158, 231, 0.25);
}

/* 统计卡片 */
.statistics-card {
	position: relative;
	border-radius: 32rpx;
	margin-bottom: 40rpx;
	overflow: hidden;
	background: var(--theme-gradient);
	box-shadow: 0 12rpx 36rpx rgba(0, 0, 0, 0.1);
	backdrop-filter: blur(10px);
}

.card-bg {
	position: absolute;
	width: 100%;
	height: 100%;
	opacity: 0.1;
}

.stat-content {
	position: relative;
	padding: 48rpx 40rpx;
	display: flex;
	justify-content: space-around;
	align-items: center;
	z-index: 1;
}

.stat-item {
	display: flex;
	flex-direction: column;
	align-items: center;
	position: relative;
}

.stat-value {
	color: #ffffff;
	font-size: 60rpx;
	font-weight: 600;
	margin-bottom: 16rpx;
	font-family: 'DIN Alternate', Arial, sans-serif;
	line-height: 1.2;
	text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
}

.stat-label {
	color: rgba(255, 255, 255, 0.95);
	font-size: 28rpx;
	font-weight: 500;
	letter-spacing: 2rpx;
}

.stat-divider {
	width: 2rpx;
	height: 100rpx;
	background: linear-gradient(to bottom,
			rgba(255, 255, 255, 0),
			rgba(255, 255, 255, 0.3),
			rgba(255, 255, 255, 0));
}

.stat-chinese {
	font-size: 24rpx;
	color: #666666;
	margin-top: 8rpx;
}

/* 操作按钮 */
.quick-actions {
	display: flex;
	gap: 24rpx;
	margin-bottom: 40rpx;
	padding: 0 4rpx;
}

.action-btn {
	flex: 1;
	padding: 32rpx;
	border-radius: 24rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 16rpx;
	box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.06);
	transition: all 0.3s ease;
	font-size: 30rpx;
	font-weight: 500;
}

.action-btn.primary {
	background: var(--theme-gradient);
	color: #ffffff;
	text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
}

.action-btn.secondary {
	background-color: var(--theme-card);
	color: var(--theme-primary);
	border: 1px solid rgba(0, 0, 0, 0.04);
}

.action-btn:active {
	transform: scale(0.98);
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.04);
}

.btn-icon {
	font-size: 32rpx;
	font-weight: bold;
}

/* 搜索栏 */
.search-section {
	margin-bottom: 40rpx;
	padding: 0 4rpx;
}

.search-bar {
	background-color: var(--theme-card);
	border-radius: 20rpx;
	padding: 24rpx 32rpx;
	display: flex;
	align-items: center;
	box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.04);
	transition: all 0.3s ease;
	border: 1px solid rgba(0, 0, 0, 0.02);
}

.search-icon {
	font-size: 36rpx;
	color: var(--theme-primary);
	margin-right: 24rpx;
}

.search-input {
	flex: 1;
	font-size: 28rpx;
	color: var(--theme-text);
	font-weight: 500;
}

/* 列表样式 */
.gift-list {
	height: calc(100vh - 630rpx);
	/* padding: 44rpx 0; */
	box-sizing: border-box;
	background-color: transparent;
}

.gift-item {
	background-color: var(--theme-card);
	border-radius: 24rpx;
	padding: 32rpx;
	margin-bottom: 24rpx;
	box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.04);
	transition: all 0.3s ease;
	border: 1px solid rgba(0, 0, 0, 0.02);
}

.gift-item:active {
	transform: scale(0.98);
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.02);
}

.gift-main {
	display: flex;
	justify-content: space-between;
	align-items: flex-start;
	margin-bottom: 24rpx;
}

.guest-info {
	display: flex;
	align-items: center;
	gap: 16rpx;
}

.guest-name {
	font-size: 34rpx;
	color: var(--theme-text);
	font-weight: 600;
	line-height: 1.4;
}

.gift-type-tag {
	font-size: 24rpx;
	padding: 4rpx 16rpx;
	border-radius: 24rpx;
	transition: all 0.3s ease;
	line-height: 1.4;
	display: inline-flex;
	align-items: center;
	justify-content: center;
	font-weight: 500;
	flex-shrink: 0;
}

.gift-amount {
	display: flex;
	flex-direction: column;
	align-items: flex-end;
}

.amount {
	font-size: 32rpx;
	color: #4080FF;
	font-weight: 600;
}

.amount-chinese {
	font-size: 24rpx;
	color: #666666;
	margin-left: 8rpx;
}

.gift-details {
	display: flex;
	flex-direction: column;
	gap: 12rpx;
	margin-top: 8rpx;
}

.gift-date {
	font-size: 24rpx;
	color: var(--theme-text-light);
	line-height: 1.4;
}

.gift-remark {
	font-size: 26rpx;
	color: var(--theme-primary);
	background-color: var(--theme-primary-light);
	padding: 10rpx 20rpx;
	border-radius: 12rpx;
	border: 1px solid var(--theme-primary-border);
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
	max-width: 100%;
	box-sizing: border-box;
	line-height: 1.4;
	font-weight: 500;
}

/* 主题切换按钮 */
.theme-switch {
	position: fixed;
	left: 0;
	top: 0;
	width: 80rpx;
	height: 80rpx;
	border-radius: 50%;
	background-color: var(--theme-card);
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 101;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
	backdrop-filter: blur(10px);
	will-change: transform;
	touch-action: none;
	transition: all 0.3s ease;
}

.theme-icon {
	font-size: 40rpx;
	transition: all 0.3s ease;
}

/* 弹窗样式 */
.modal {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.6);
	display: flex;
	justify-content: center;
	align-items: center;
	z-index: 999;
}

.modal-content {
	background-color: var(--theme-card);
	border-radius: 32rpx;
	width: 85%;
	max-height: 85vh;
	overflow-y: auto;
	transition: all 0.3s ease;
	box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.15);
}

.modal-header {
	padding: 32rpx 40rpx;
	display: flex;
	justify-content: space-between;
	align-items: center;
	border-bottom: 1rpx solid var(--theme-background);
}

.modal-title {
	font-size: 36rpx;
	font-weight: 600;
	color: var(--theme-text);
}

.modal-close {
	font-size: 44rpx;
	color: var(--theme-text-light);
	padding: 12rpx;
	width: 64rpx;
	height: 64rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	margin: -12rpx;
	border-radius: 50%;
	transition: all 0.3s ease;
}

.modal-close:active {
	background-color: var(--theme-background);
}

.modal-body {
	padding: 40rpx;
}

.form-group {
	display: flex;
	gap: 32rpx;
	margin-bottom: 32rpx;
}

.form-item {
	flex: 1;
	margin-bottom: 32rpx;
}

.form-label {
	font-size: 28rpx;
	color: var(--theme-text-secondary);
	margin-bottom: 16rpx;
	display: block;
	font-weight: 500;
}

.form-label.required::after {
	content: '*';
	color: #FF4D4F;
	margin-left: 8rpx;
}

.form-input,
.form-picker,
.form-textarea {
	width: 100%;
	background-color: var(--theme-background);
	border-radius: 16rpx;
	padding: 24rpx 32rpx;
	font-size: 30rpx;
	color: var(--theme-text);
	box-sizing: border-box;
	min-height: 88rpx;
	transition: all 0.3s ease;
	border: 2rpx solid transparent;
}

.form-input:focus,
.form-textarea:focus {
	border-color: var(--theme-primary);
	box-shadow: 0 0 0 2rpx var(--theme-primary-light);
}

.form-textarea {
	height: 180rpx;
	line-height: 1.5;
}

.modal-footer {
	padding: 32rpx 40rpx;
	display: flex;
	justify-content: flex-end;
	gap: 24rpx;
	border-top: 1rpx solid var(--theme-background);
}

.modal-btn {
	padding: 24rpx 48rpx;
	border-radius: 16rpx;
	font-size: 30rpx;
	min-width: 180rpx;
	text-align: center;
	transition: all 0.3s ease;
	font-weight: 500;
}

.modal-btn.cancel {
	background-color: var(--theme-background);
	color: var(--theme-text-secondary);
	border: 1rpx solid var(--theme-background);
}

.modal-btn.confirm {
	background: var(--theme-gradient);
	color: #ffffff;
	box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
}

.modal-btn:active {
	transform: scale(0.98);
	opacity: 0.9;
}

/* 空状态 */
.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 100rpx 0;
}

.empty-icon {
	width: 200rpx;
	height: 200rpx;
	margin-bottom: 30rpx;
}

.empty-text {
	color: var(--theme-text-light);
	font-size: 28rpx;
}

/* 滚动条 */
::-webkit-scrollbar {
	width: 0;
	height: 0;
	background-color: transparent;
	display: none;
}

/* 页面配置 */
page {
	height: 100vh;
	overflow: hidden;
	background-color: var(--theme-background);
	transition: all 0.3s ease;
}

/* 导出选项弹窗样式 */
.export-modal {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.6);
	display: flex;
	justify-content: center;
	align-items: flex-end;
	z-index: 999;
	animation: modalFadeIn 0.3s ease;
}

.export-content {
	width: 100%;
	background-color: var(--theme-card);
	border-radius: 32rpx 32rpx 0 0;
	overflow: hidden;
	transform: translateY(100%);
	animation: slideUp 0.3s ease forwards;
}

.export-header {
	padding: 32rpx 40rpx;
	display: flex;
	justify-content: space-between;
	align-items: center;
	border-bottom: 1rpx solid var(--theme-background);
}

.export-title {
	font-size: 32rpx;
	font-weight: 600;
	color: var(--theme-text);
}

.export-close {
	font-size: 40rpx;
	color: var(--theme-text-light);
	padding: 12rpx;
	width: 64rpx;
	height: 64rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	margin: -12rpx;
	border-radius: 50%;
}

.export-options {
	padding: 32rpx 0;
}

.export-option {
	display: flex;
	align-items: center;
	padding: 28rpx 32rpx;
	transition: all 0.3s ease;
	position: relative;
	margin: 0 32rpx;
	border-radius: 24rpx;
	background-color: var(--theme-card);
	border: 2rpx solid rgba(0, 0, 0, 0.08);
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.02);
}

.export-option:not(:last-child) {
	margin-bottom: 24rpx;
}

.dark-mode .export-option {
	border-color: rgba(255, 255, 255, 0.08);
}

.export-option:active {
	transform: scale(0.98);
	background-color: rgba(0, 0, 0, 0.02);
}

.dark-mode .export-option:active {
	background-color: rgba(255, 255, 255, 0.02);
}

.option-icon-wrapper {
	width: 80rpx;
	height: 80rpx;
	border-radius: 20rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-right: 24rpx;
	position: relative;
	overflow: hidden;
	box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.1);
}

/* 为不同的图标设置不同的渐变背景 */
.export-option:nth-child(1) .option-icon-wrapper {
	background: linear-gradient(135deg, #36D1DC 0%, #5B86E5 100%);
}

.export-option:nth-child(2) .option-icon-wrapper {
	background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
}

.option-icon-wrapper::before {
	content: "";
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: linear-gradient(45deg,
			rgba(255, 255, 255, 0.3) 0%,
			rgba(255, 255, 255, 0.1) 50%,
			rgba(255, 255, 255, 0) 100%);
	z-index: 1;
}

.option-icon-wrapper::after {
	content: "";
	position: absolute;
	top: -50%;
	left: -50%;
	right: -50%;
	bottom: -50%;
	background: radial-gradient(circle at 50% 50%,
			rgba(255, 255, 255, 0.25) 0%,
			transparent 60%);
	opacity: 0.6;
	z-index: 2;
	transform: scale(1);
	transition: transform 0.3s ease;
}

.export-option:active .option-icon-wrapper::after {
	transform: scale(0.9);
}

.option-icon {
	font-size: 44rpx;
	color: #ffffff;
	position: relative;
	z-index: 3;
	text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.15);
}

.option-info {
	flex: 1;
	display: flex;
	flex-direction: column;
	gap: 12rpx;
}

.option-title {
	font-size: 32rpx;
	color: var(--theme-text);
	font-weight: 600;
}

.option-desc {
	font-size: 26rpx;
	color: var(--theme-text-light);
	line-height: 1.4;
}

@keyframes modalFadeIn {
	from {
		opacity: 0;
	}

	to {
		opacity: 1;
	}
}

@keyframes slideUp {
	from {
		transform: translateY(100%);
	}

	to {
		transform: translateY(0);
	}
}

/* 加载更多和无更多数据样式 */
.loading-more,
.no-more {
	text-align: center;
	padding: 24rpx 0;
	color: var(--theme-text-light);
	font-size: 24rpx;
	opacity: 0.8;
}

.loading-more {
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 12rpx;
}

.loading-more::after {
	content: "";
	width: 32rpx;
	height: 32rpx;
	border: 2rpx solid var(--theme-text-light);
	border-top-color: transparent;
	border-radius: 50%;
	animation: loading 0.8s linear infinite;
}

.no-more {
	position: relative;
	margin: 24rpx 40rpx;
}

.no-more::before,
.no-more::after {
	content: "";
	position: absolute;
	top: 50%;
	width: 120rpx;
	height: 1px;
	background: var(--theme-text-light);
	opacity: 0.2;
}

.no-more::before {
	left: 25%;
	transform: translateX(-50%);
}

.no-more::after {
	right: 25%;
	transform: translateX(50%);
}

@keyframes loading {
	from {
		transform: rotate(0deg);
	}

	to {
		transform: rotate(360deg);
	}
}
</style>